from django.http import JsonResponse
from rest_framework import viewsets
from rest_framework.response import Response
from app01.utils.form.Psychologist import PsychologistModelForm_login,PsychologistForm_add
from app01.utils.serializers.Psychologist_ser import Psychologist_class_list
from app01.utils.form.Classroom_form import Classroom_form_add
from app01 import models
from django.core.exceptions import ObjectDoesNotExist
from app01.utils.serializers.Student_ser import StudentSerializer_list
import json
from django.utils import timezone
from django.db.models import Max
import random
from django.core.cache import cache
import logging

logger = logging.getLogger(__name__)
from django.views.decorators.csrf import csrf_exempt
#psy_id = 
class Psychologist_classroom_list(viewsets.ModelViewSet):
    queryset = models.Classroom.objects.all()
    serializer_class = Psychologist_class_list

    def list(self, request, *args, **kwargs):
        user_id = request.session.get("user_id")
        psychologist = models.Psychologist.objects.get(psychologist_id=user_id)
        queryset = psychologist.teacher_classrooms.all()
        serializer = self.get_serializer(queryset, many=True)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)
    
@csrf_exempt
def Psychologist_login(request):
    if request.method == "POST":
        data = json.loads(request.body)['data']
        username = data['username']
        password = data['password']
        if username[0] == 'T':
            try:
                psychologist = models.Psychologist.objects.get(psychologist_id=username, password=password)
                request.session['user_id'] = psychologist.psychologist_id
                print(request.session['user_id'])
                request.session.set_expiry(3600*24*7)  # 设置 session 过期时间，例如 1 小时
                response = JsonResponse({'status': True, 'message': '教师登陆成功', 'id': username})
                response.set_cookie('sessionid', request.session.session_key, samesite='None', secure=True)
                return response
            except models.Psychologist.DoesNotExist:
                return JsonResponse({'status': False, 'message': '用户名或密码错误'})
        elif username[0] == 'S':
            try:
                police = models.Police.objects.get(police_id=username, password=password)
                request.session['user_id'] = police.police_id
                request.session.set_expiry(3600*24*7)
                response = JsonResponse({'status':True,'message':'安保人员登陆成功','id':police.police_id})
                response.set_cookie('sessionid', request.session.session_key, samesite='None', secure=True)
                return response
                #return JsonResponse({'status': True, 'message': '安保人员登录成功', 'id': username})
            except models.Police.DoesNotExist:
                return JsonResponse({'status': False, 'message': '用户名或密码错误'})
        else:
            try:
                psychologist = models.Psychologist.objects.get(phone_number=username, password=password)
                request.session["user_id"] = psychologist.psychologist_id
                print(request.session['user_id'])
                print('手机号')
                request.session.set_expiry(3600*24*7)    
                logger.debug(f"User {psychologist.phone_number} logged in")
                print(request.COOKIES)
                response = JsonResponse({'status': True, 'message': '教师登陆成功', 'id': psychologist.psychologist_id})
                response.set_cookie('sessionid', request.session.session_key, samesite='None', secure=True)
                return response
            except models.Psychologist.DoesNotExist:
                try:
                    police = models.Police.objects.get(phone_number=username, password=password)
                    request.session['user_id'] = police.phone_id
                    request.session.set_expiry(3600)
                    response = JsonResponse({'status':True,'message':'安保人员登陆成功','id':police.police_id})
                    response.set_cookie('sessionid', request.session.session_key, samesite='None', secure=True)
                    return response
                except models.Police.DoesNotExist:
                    return JsonResponse({'status': False, 'message': '用户名或密码错误'})
    else:
        return JsonResponse({'status': False, 'message': '只接受 POST 请求'})

@csrf_exempt
def Psychologist_add(request):
    if request.method == "POST":
        data = json.loads(request.body)
        print(data)
        
        form = PsychologistForm_add(data=data['data'])
        if form.is_valid():
            # 获取当前表中的自增ID的最大值
            max_id = models.Psychologist.objects.all().aggregate(Max('id'))['id__max']
            if max_id is None:
                max_id = 0
            next_id = max_id + 1
            # 生成Psychologist_id
            current_year = timezone.now().year
            psychologist_id = f"T{current_year}0806{next_id}"
            # 保存表单之前设置Psychologist_id
            form.instance.psychologist_id = psychologist_id
            form.save()
            return JsonResponse({'status': True, 'message': '注册成功','id':psychologist_id})
        return JsonResponse({'status': False, 'message': '该用户名已经存在'})
    
    elif request.method =="GET":
            verification_code = ''.join(random.choices('0123456789', k=6))
            print(verification_code)
            return JsonResponse({'status':True,'message':verification_code})
        
    return JsonResponse({'status': False, 'errors': '请求发送错误'})
# @csrf_exempt
# def Psychologist_classroom_list(request):
#     if request.method=='GET':
#             user_id = request.session.get("user_id")
#             psychologist = models.Psychologist.objects.get(psychologist_id=user_id)
#             classrooms = psychologist.teacher_classrooms.all()
#             class_data = {classroom.class_name: classroom.student_count for classroom in classrooms}
#             # return JsonResponse({'status':True,'data':class_data})
#             if classrooms.exists():
#                 class_data = {classroom.class_name: classroom.student_count for classroom in classrooms}
#                 return JsonResponse({'status': True, 'data': class_data})
#             else:
#                 return JsonResponse({'status': False, 'message': '还没有班级'})
#     return JsonResponse({'status':False,'data':"未发生post请求"})
@csrf_exempt
def Psychologist_classroom_add(request):
    if request.method=='POST':
        user_id = request.session.get("user_id")
        data = json.loads(request.body)['data']
        psychologist = models.Psychologist.objects.get(psychologist_id=user_id)
        form = Classroom_form_add(data = data)
        if form.is_valid():
            form.instance.class_teacher = psychologist
            form.save()
            return JsonResponse({'status': True, 'message': '班级添加成功'})
        return JsonResponse({'status': False, 'message': '班级已经存在'})
    return JsonResponse({'status': False, 'message': '未发生POST请求'})
    
def Student_delete(request):   
    if request.method == 'GET':
        stu_id = request.GET.get('stu_id')
        models.Student.objects.get(student_id=stu_id).delete()
        return JsonResponse({'status':True,'message':'删除成功'})
    else :
        return JsonResponse({'status':False,'message':'删除失败'})
            
def logout(request):
    if request.method == 'GET':
        request.session.clear()
        return JsonResponse({'status':True,'message':'退出成功'})
    else:
        return JsonResponse({'status':False,'message':'退出失败'})

    
    
    
    
